<?php
namespace oauth2user\controllers;

use common\libraries\Curl;
use common\libraries\Http;
use oauth2user\components\Category;
use Yii;
use yii\web\Controller;
/**
 * ApiController
 */
class ApiController extends Controller{

    public function actionIndex(){

        $cates = Yii::$app->params["apiCategories"];

        $host = Yii::$app->params["oauth2_server_host"];

        $data = [
            'host' => $host,
            'cates' => $cates,
        ];


        return $this->renderPartial('index', $data);
    }

    public function actionDetail(){

        $uri = isset($_GET["uri"]) ? $_GET["uri"] : "";

        $api = Category::getApiByUri($uri);

        $host = Yii::$app->params["oauth2_server_host"];

        $data = [
            'host' => $host,
            'api' => $api,
        ];

        return $this->renderPartial('detail', $data);
    }

    public function actionCurl(){

        $uri = isset($_GET["uri"]) ? addslashes($_GET["uri"]) : "";
        $api = Category::getApiByUri($uri);

        $data = [];
        if(isset($api["params"]) && is_array($api["params"])) {
            foreach ($api["params"] as $param) {
                $data[$param["name"]] = isset($_POST[$param["name"]]) ? $_POST[$param["name"]] : $param["default"];
            }
        }

        echo "请求参数：";
        echo '<pre>';print_r($data);

        $host = Yii::$app->params["oauth2_server_host"];
        $request_url = $host.$api["uri"];

        echo "请求地址：".$request_url."<br>";

        echo "---------------------------<br>";


        if(strtoupper($api["method"]) == 'POST'){
            $result = Curl::post_formdata2($request_url, $data);
        }else{
            //$r = Curl::($request_url, $data, $header);
        }

        print_r($result);
        echo '<br>';

        if($result_array = json_decode($result, true)){
            print_r($result_array);
        }

    }

    public function actionPhp(){

        $uri = isset($_GET["uri"]) ? addslashes($_GET["uri"]) : "";
        $api = Category::getApiByUri($uri);


        $data = [];
        if(isset($api["params"]) && is_array($api["params"])) {
            foreach ($api["params"] as $param) {
                $data[$param["name"]] = isset($_POST[$param["name"]]) ? $_POST[$param["name"]] : $param["default"];
            }
        }

        echo "请求参数：";
        echo '<pre>';print_r($data);

        $host = Yii::$app->params["oauth2_server_host"];
        $request_url = $host.$api["uri"];

        echo "请求地址：".$request_url."<br>";

        echo "---------------------------<br>";



        try{
            $result = Http::file_get_contents_post($request_url, $data);
        }catch (\Exception $e){
            print_r($e->getMessage());exit;
        }



        print_r($result);


        if($result_array = json_decode($result, true)){
            print_r($result_array);
        }

    }


}
